﻿
using Cms.Core.Infrastructure.Common;
using Cms.Core.Infrastructure.Dependency;
using Cms.Core.Infrastructure.Helps;
using Cms.Core.Infrastructure.Log;
using Cms.Core.Infrastructure.Ui;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Cms.Core.AspNetMvc.Mvc.Middleware
{
    /// <summary>
    /// 全局异常中间件
    /// </summary>
    public class ExceptionHandlingMiddleware
    {

        private readonly RequestDelegate _next;
        private ExceptionHandlerOptions _options;

        public ExceptionHandlingMiddleware(RequestDelegate next, IOptions<ExceptionHandlerOptions> options)
        {
            _next = next;
            _options = options.Value;
        }

        public async Task Invoke(HttpContext context)
        {

            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                var log = ServiceLocator.Instance.GetService<ILoggerHelper>();
                
                log.Error(this,ex);
                await HandleExceptionAsync(context, ex);
            }
        }


        private Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            if (context.Request.IsJsonContextType())
            {

                //var jsonSettings = new JsonSerializerSettings
                //{

                //    //ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(),
                //    ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),

                //};
                AjaxResult result = new AjaxResult(ex.Message,AjaxResultType.Error);
                result.Success = result.Successed();
                return context.Response.WriteAsync(result.ToJson());
            }
            context.Response.ContentType = "text/html;charset=utf-8";
            return context.Response.WriteAsync($"服务器错误，错误信息{ex.Message}");
        }
    }

    public static class ErrorHandlingExtensions
    {
        /// <summary>
        /// 异常中间件
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>

        public static IApplicationBuilder UseErrorHandling(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ExceptionHandlingMiddleware>();
        }
    }
}
